// pages/history/history.js
Page({
  data: {
    // 筛选条件
    recordType: 'all', // all, blood, medication
    startDate: '',
    endDate: '',
    today: '',
    searchKeyword: '',
    
    // 记录数据
    allRecords: [],
    filteredRecords: [],
    groupedRecords: [],
    hasRecords: false,
    
    // 交互状态
    showDeleteDialog: false,
    recordToDelete: null,
    showExportSuccess: false
  },

  onLoad(options) {
    // 初始化日期
    const today = this.formatDate(new Date(), 'yyyy-MM-dd');
    const defaultStartDate = this.formatDate(new Date(Date.now() - 30 * 24 * 60 * 60 * 1000), 'yyyy-MM-dd');
    
    this.setData({
      today: today,
      startDate: defaultStartDate,
      endDate: today
    });
    
    // 如果从首页带参数跳转，设置对应的记录类型
    if (options.type === 'medication') {
      this.setData({
        recordType: 'medication'
      });
    }
    
    // 加载记录数据
    this.loadRecords();
    
    // 监听存储变化
    wx.onStorageChange(this.handleStorageChange);
  },

  onShow() {
    // 页面显示时刷新数据
    this.loadRecords();
  },

  onUnload() {
    // 页面卸载时移除监听
    wx.offStorageChange(this.handleStorageChange);
  },

  // 加载记录数据
  loadRecords() {
    // 获取所有记录
    const bloodRecords = wx.getStorageSync('bloodPressureRecords') || [];
    const medicationRecords = wx.getStorageSync('medicationRecords') || [];
    
    // 统一格式并添加类型标识
    const formattedBloodRecords = bloodRecords.map(record => ({
      ...record,
      type: 'blood'
    }));
    
    const formattedMedicationRecords = medicationRecords.map(record => ({
      ...record,
      type: 'medication'
    }));
    
    // 合并所有记录并按时间排序
    const allRecords = [...formattedBloodRecords, ...formattedMedicationRecords]
      .sort((a, b) => new Date(b.recordTime) - new Date(a.recordTime));
    
    this.setData({
      allRecords: allRecords
    }, () => {
      // 应用筛选条件
      this.applyFilters();
    });
  },

  // 应用筛选条件
  applyFilters() {
    const { allRecords, recordType, startDate, endDate, searchKeyword } = this.data;
    
    // 筛选记录
    let filteredRecords = [...allRecords];
    
    // 类型筛选
    if (recordType !== 'all') {
      filteredRecords = filteredRecords.filter(record => record.type === recordType);
    }
    
    // 日期范围筛选
    if (startDate && endDate) {
      const start = new Date(startDate);
      const end = new Date(endDate);
      end.setHours(23, 59, 59, 999); // 设置为结束日的最后一刻
      
      filteredRecords = filteredRecords.filter(record => {
        const recordDate = new Date(record.recordTime);
        return recordDate >= start && recordDate <= end;
      });
    }
    
    // 关键词搜索
    if (searchKeyword) {
      const keyword = searchKeyword.toLowerCase();
      filteredRecords = filteredRecords.filter(record => {
        // 血压记录搜索字段
        if (record.type === 'blood') {
          return (
            record.systolic.toString().includes(keyword) ||
            record.diastolic.toString().includes(keyword) ||
            record.heartRate.toString().includes(keyword) ||
            (record.notes && record.notes.toLowerCase().includes(keyword)) ||
            record.recordTime.toLowerCase().includes(keyword)
          );
        } 
        // 用药记录搜索字段
        else {
          return (
            record.medicationName.toLowerCase().includes(keyword) ||
            record.status.toLowerCase().includes(keyword) ||
            (record.notes && record.notes.toLowerCase().includes(keyword)) ||
            record.recordTime.toLowerCase().includes(keyword)
          );
        }
      });
    }
    
    // 按日期分组
    const groupedRecords = this.groupRecordsByDate(filteredRecords);
    
    this.setData({
      filteredRecords: filteredRecords,
      groupedRecords: groupedRecords,
      hasRecords: filteredRecords.length > 0
    });
  },

  // 按日期分组记录
  groupRecordsByDate(records) {
    if (!records.length) return [];
    
    const groups = {};
    
    records.forEach(record => {
      // 提取日期部分作为分组键
      const recordDate = new Date(record.recordTime);
      const dateKey = this.formatDate(recordDate, 'yyyy-MM-dd');
      const displayDate = this.formatDate(recordDate, 'yyyy年MM月dd日');
      
      // 创建或添加到分组
      if (!groups[dateKey]) {
        groups[dateKey] = {
          date: displayDate,
          records: []
        };
      }
      
      groups[dateKey].records.push(record);
    });
    
    // 将对象转换为数组
    return Object.values(groups);
  },

  // 记录类型筛选变化
  onRecordTypeChange(e) {
    this.setData({
      recordType: e.detail.value
    }, () => {
      this.applyFilters();
    });
  },

  // 开始日期变化
  onStartDateChange(e) {
    this.setData({
      startDate: e.detail.value
    }, () => {
      this.applyFilters();
    });
  },

  // 结束日期变化
  onEndDateChange(e) {
    this.setData({
      endDate: e.detail.value
    }, () => {
      this.applyFilters();
    });
  },

  // 搜索输入
  onSearchInput(e) {
    this.setData({
      searchKeyword: e.detail.value
    }, () => {
      this.applyFilters();
    });
  },

  // 清除搜索
  clearSearch() {
    this.setData({
      searchKeyword: ''
    }, () => {
      this.applyFilters();
    });
  },

  // 确认删除记录
  confirmDelete(e) {
    const { id } = e.currentTarget.dataset;
    
    this.setData({
      showDeleteDialog: true,
      recordToDelete: id
    });
  },

  // 取消删除
  cancelDelete() {
    this.setData({
      showDeleteDialog: false,
      recordToDelete: null
    });
  },

  // 删除记录
  deleteRecord() {
    if (!this.data.recordToDelete) return;
    
    const recordId = this.data.recordToDelete;
    
    // 获取所有记录
    let bloodRecords = wx.getStorageSync('bloodPressureRecords') || [];
    let medicationRecords = wx.getStorageSync('medicationRecords') || [];
    
    // 查找并删除记录
    const bloodIndex = bloodRecords.findIndex(record => record.id === recordId);
    const medicationIndex = medicationRecords.findIndex(record => record.id === recordId);
    
    if (bloodIndex !== -1) {
      bloodRecords.splice(bloodIndex, 1);
      wx.setStorageSync('bloodPressureRecords', bloodRecords);
    } else if (medicationIndex !== -1) {
      medicationRecords.splice(medicationIndex, 1);
      wx.setStorageSync('medicationRecords', medicationRecords);
    }
    
    // 更新界面
    this.setData({
      showDeleteDialog: false,
      recordToDelete: null
    });
    
    // 重新加载记录
    this.loadRecords();
    
    // 显示成功提示
    wx.showToast({
      title: '记录已删除',
      icon: 'success',
      duration: 1500
    });
  },

  // 导出数据
  exportData() {
    // 准备导出数据
    const exportData = {
      exportTime: this.formatDate(new Date(), 'yyyy-MM-dd HH:mm:ss'),
      bloodPressureRecords: wx.getStorageSync('bloodPressureRecords') || [],
      medicationRecords: wx.getStorageSync('medicationRecords') || []
    };
    
    // 转换为JSON字符串
    const jsonData = JSON.stringify(exportData, null, 2);
    
    // 保存到本地文件
    const fileName = `血压用药记录_${this.formatDate(new Date(), 'yyyyMMddHHmmss')}.json`;
    
    wx.setStorageSync(fileName, jsonData);
    
    // 显示导出成功提示
    this.setData({
      showExportSuccess: true
    });
    
    setTimeout(() => {
      this.setData({
        showExportSuccess: false
      });
    }, 2000);
    
    // 提示用户
    wx.showModal({
      title: '导出成功',
      content: `数据已导出为JSON文件：${fileName}\n可在"我的文件"中查看`,
      showCancel: false,
      confirmText: '知道了'
    });
  },

  // 处理存储变化
  handleStorageChange(e) {
    if (e.key === 'bloodPressureRecords' || e.key === 'medicationRecords') {
      this.loadRecords();
    }
  },

  // 格式化日期
  formatDate(date, format) {
    const year = date.getFullYear();
    const month = date.getMonth() + 1;
    const day = date.getDate();
    const hours = date.getHours();
    const minutes = date.getMinutes();
    
    // 补零函数
    const padZero = num => num < 10 ? `0${num}` : num;
    
    if (format === 'yyyy-MM-dd') {
      return `${year}-${padZero(month)}-${padZero(day)}`;
    } else if (format === 'yyyy年MM月dd日') {
      return `${year}年${padZero(month)}月${padZero(day)}日`;
    } else if (format === 'yyyyMMddHHmmss') {
      return `${year}${padZero(month)}${padZero(day)}${padZero(hours)}${padZero(minutes)}`;
    }
    
    return `${year}-${padZero(month)}-${padZero(day)} ${padZero(hours)}:${padZero(minutes)}`;
  }
})